package com.library.dao.impl;

import com.library.bean.User;
import com.library.dao.BaseDao;
import com.library.dao.UserDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDaoImpl implements UserDao {
    @Override
    public User queryByUser(User user) {
        return null;
    }

    @Override
    public User queryByUser(String user$account, String user$pass) {
        Connection connection = BaseDao.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        String sql = "SELECT * FROM users WHERE userAccount  = ? AND userpass = ?";
        System.out.println(sql);
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, user$account);
            ps.setString(2, user$pass);
            rs = ps.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setUser_id(rs.getInt("userId"));
                user.setUser_account(rs.getString("userAccount"));
                user.setUser_password(rs.getString("userpass"));
                user.setReal_name(rs.getString("realName"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(connection, ps, rs);
        }
        return user;
    }

    @Override
    public User queryByUser_account(String user$account) {
        Connection connection = BaseDao.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        String sql = "SELECT * FROM users WHERE userAccount = ?";
        System.out.println(sql);
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, user$account);
            rs = ps.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setUser_id(rs.getInt("userId"));
                user.setUser_account(rs.getString("userAccount"));
                user.setUser_password(rs.getString("userpass"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(BaseDao.conn, BaseDao.ps, rs);
        }
        return user;
    }

    @Override
    public int insertUser(User user) {
        String sql = "INSERT INTO user_info(userAccount,userpass,realName) VALUES(?,?,?)";
        System.out.println(sql);
        Object[] param = {user.getUser_account(), user.getUser_password(), user.getReal_name()};
        return BaseDao.executeUpdate(sql,param);
    }
}
